/*使用多路复用实现并发服务器模型——客户端*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

int fd;
void * recv_mess(void *arg)
{
	char buf[50];
	int ret;
	pthread_detach(pthread_self());
	while (1) {
		bzero(buf, 50);
		ret = recv(fd, buf, sizeof(buf), 0);
		printf("recv srv string: %s", buf);
		printf("recv led=%d\n", ret);
		
	}
	
	pthread_exit(NULL);
}

int main(void)
{
	
	int ret;

	//1.socket() 买电话
	
	fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd == -1) {
		perror("socket");
		exit(1);
	}
	int on=1;
	setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)); //重用端口号 on 设置为真

	//3.connect() 打电话 
	struct sockaddr_in server;
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = inet_addr("192.168.104.89");
	server.sin_port = htons(12001);
	ret = connect(fd, (struct sockaddr *)&server, sizeof(server));	
	if (ret == -1) {
		perror("connect");
		exit(1);
	}

	//创建线程
	pthread_t tid;
	pthread_create(&tid, NULL, recv_mess, NULL);
	
	//4.send()发送
	char buf[50] ;
	while (1) {
		bzero(buf, 50);
		printf("pls input a string:");
		fgets(buf, 50, stdin); //阻塞
		ret = write(fd, buf, strlen(buf));
		printf("write len=%d\n", ret);
		if (strncmp(buf, "quit", 4) == 0) break;
	}

	
	//5.close() 挂电话
	close(fd);
	

	return 0;
}

